package org.pas.fb2;

import org.pas.fb2.tag.RootTag;
import org.pas.fb2.tag.Tag;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class MainFb2 {

    public static void main(String[] args) throws Exception {

        if (args.length == 0) {
            usage();
            return;
        }

        final String fb2Name = args[0];
        final PrintStream out;
        if (args.length >= 2) {
            String txtName = args[1];
            out = new PrintStream(new FileOutputStream(txtName), true, "windows-1251");
        } else {
            out = new PrintStream(new FileOutputStream(changeExtention(fb2Name)), true, "windows-1251");
        }

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        Fb2Handler fb2Handler = new Fb2Handler(out);
        xmlReader.setContentHandler(fb2Handler);
        xmlReader.parse(new InputSource(new FileInputStream(fb2Name)));
    }

    private static void usage() {
        //todo: show usage and other information
        String usage = "" +
                "convert files from fb2 (fiction book v2) format into plain text\n" +
                "\n" +
                "todo: show usage and other information\n";
        System.out.print(usage);
    }

    static String changeExtention(String name) {
        int n = name.lastIndexOf('.');
        if (n != -1) {
            name = name.substring(0, n);
        }
        return name + ".book";
    }

    static class Fb2Handler extends DefaultHandler2 {

        private final PrintStream out;
        private Locator documentLocator;
        private Tag tag;

        Fb2Handler(PrintStream out) {
            this.out = out;
        }

        @Override
        public void setDocumentLocator(Locator locator) {
            documentLocator = locator;
        }

        public Locator getDocumentLocator() {
            return documentLocator;
        }

        @Override
        public void startDocument() throws SAXException {
            tag = new RootTag(out);
        }

        @Override
        public void endDocument() throws SAXException {
            out.close();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            tag = tag.onChild(qName);
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            tag = tag.onClose(qName);
        }

        @Override
        public void characters(char ch[], int start, int length) throws SAXException {
            tag.onChars(ch, start, length);
        }
    }
}
